package contactbook.dao.impl;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import contactbook.dao.GroupDAOInterface;
import contactbook.model.Group;

@Stateless
@Local(GroupDAOInterface.class)
public class GroupDAO implements GroupDAOInterface {

	private static final String GET_GROUP_BY_NAME = "SELECT DISTINCT g FROM Group g WHERE g.name = :name";
	
	@PersistenceContext(unitName = "ContactBookPU")
	protected EntityManager em;
	
	public GroupDAO() {}
	
	@Override
	public Group addGroup(Group group) {
		em.persist(group);
		return group;
	}

	@Override
	public void deleteGroup(int groupId) {
		Group group = em.find(Group.class, groupId);
		em.remove(group);
	}

	@Override
	public Group findById(int groupId) {
		return em.find(Group.class, groupId);
	}
	
	@Override
	public Group findByName(String name) {
		Query q = em.createQuery(GET_GROUP_BY_NAME);
		q.setParameter("name", name);
		return (Group) q.getSingleResult();
	}
	
	@Override
	public boolean exists(int groupId) {
		return em.find(Group.class, groupId) != null;
	}
	
	@Override
	public void update(Group group) {
		em.merge(group);
		em.flush();
	}
	
	@Override
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
}
